package com.twu.biblioteca.Domain;

import com.twu.biblioteca.Entity.Movie;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hjli on 9/10/14.
 */
public class MovieService {

    private List<Movie> allMovies;
    private List<Movie> moviesOnShelf;

    public MovieService(){
        allMovies = new ArrayList<Movie>();
        moviesOnShelf = new ArrayList<Movie>();
        Movie movie_one = new Movie("1","Star Trek Into Darkness","2013","J.J.Abrams",7.9);
        Movie movie_two = new Movie("2","Maleficent","2014","Robert Stromberg",7.4);
        allMovies.add(movie_one);
        allMovies.add(movie_two);
        moviesOnShelf.addAll(allMovies);
    }

    public String listMovies() {
        String result = "";
        for(Movie movie : this.moviesOnShelf){
            result += "\n"+movie.toString();
        }
        return result.replaceFirst("\\\\n","");
    }

    public String returnTo(String input) throws Exception {
        Movie movie = this.isReturnValid(input);
        String result;
        if( movie != null){
            this.moviesOnShelf.add(movie);
            result = "Thank you for returning the Movie.";
        }
        else{
            result = "That is not a valid movie to return.";
        }
        return result;
    }

    public Movie isReturnValid(String input) {
        Movie result = null;
        List<Movie> allMovies = this.allMovies;
        if(input!=null && !input.isEmpty()){
            for(Movie movie : allMovies){
                if(input.equals(movie.getId()))
                    result = movie;
                break;
            }
        }
        return result;
    }

    public String checkout(String input) throws Exception{
        Movie movie = this.isBorrowValid(input);
        String result;
        if(movie != null){
            moviesOnShelf.remove(movie);
            result = "Thank you! Enjoy the movie.";
        }
        else{
            result = "That movie is not available.";
        }
        return result;
    }

    public Movie isBorrowValid(String input) {
        Movie result = null;
        List<Movie> moviesOnShelf = this.moviesOnShelf;
        if(input!=null && !input.isEmpty()){
            for(Movie movie : moviesOnShelf){
                if(input.equals(movie.getId())){
                    result = movie;
                    break;
                }
            }
        }
        return result;
    }


}
